package com.km.noh.weatherinfo.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.km.noh.weatherinfo.R;

public class Util {
	public static final boolean DEBUG = true;
	public static final String TAG = "Weather";

	public static float dpip = -1;
	
	public static final int KB = 1024;
	public static final int MB = KB * KB;
	public static final int GB = MB * KB;
	
	private final static int CHECK_TIMEOUT = 10 * 1000;
	
	public static String convertUrlToString(String url) {
		return url.replaceAll("http://","").replaceAll(":", "").replaceAll("/", "").replaceAll("&", "_").replaceAll("\\?", "_").replaceAll("=", "_").replaceAll("\\-", "_").replaceAll("\\.", "_");
	}
	
	public static void log(String msg) {
		if (DEBUG) {
			log("debug", msg);
		}
	}
	
	public static void log(String tag, String msg) {
		if (DEBUG) {
			Log.d(tag, msg);
		}
	}
	
	public static void logWarning(Throwable e) {
		Log.w(TAG, e.toString(), e);
	}
	
	public static void logWarning(String e) {
		Log.w(TAG, e);
	}
	
	public static void logWarning(String msg, Throwable e) {
		Log.w(TAG, msg, e);
	}
	
	public static void logError(Throwable e) {
		Log.e(TAG, e.toString(), e);
	}
	
	public static void logError(String e) {
		Log.e(TAG, e);
	}
	public static void logError(String msg, Throwable e) {
		Log.e(TAG, msg, e);
	}
	
	public static int getByte(String filesize) {
		int result = 0, size=1;
		filesize = filesize.trim().toLowerCase();
		if (filesize.indexOf("k")>-1) {
			size = 1024;
			result = (int)(Double.parseDouble(filesize.substring(0,filesize.indexOf("k")))*size);
		} else if (filesize.indexOf("m")>-1) {
			size = 1024*1024;
			result = (int)(Double.parseDouble(filesize.substring(0,filesize.indexOf("m")))*size);
		} else if (filesize.indexOf("g")>-1) {
			size = 1024*1024*1024;
			result = (int)(Double.parseDouble(filesize.substring(0,filesize.indexOf("g")))*size);
		}
		return result;
	}
	
	public static String getKByte(int filesize) {
		DecimalFormat df = new DecimalFormat("0.00");
		return df.format(((double)filesize)/KB);
	}
	
	public static String getMByte(int filesize) {
		DecimalFormat df = new DecimalFormat("0.00");
		return df.format(((double)filesize)/MB);
	}
	
	public static String[] parseXmlDocument(Element e, String nodeName) {
		Vector<String> vc = new Vector<String>();
		
		NodeList node = e.getElementsByTagName(nodeName);
		for (int i=0;i<node.getLength();i++) {
			vc.add(parseXmlDocumentNode(e,nodeName,i));
		}
		return vc.toArray(new String[]{});
	}
	
	public static String parseXmlDocument(Element e, String nodeName, int num) {
		NodeList node = e.getElementsByTagName(nodeName);
		String data =node.item(num).getAttributes().getNamedItem("data").getNodeValue();
		Util.log("parseXmlDocumentData===>>"+data);
		return KMStringUtil.getStr(data);
	}
	public static String parseXmlDocumentNode(Element e, String nodeName, int num) {
		NodeList node = e.getElementsByTagName(nodeName);
		Node n1 = node.item(num);
		if (n1==null) return null;
		Node n2 = n1.getFirstChild();
		if (n2==null) return null;
		return n2.getNodeValue();
	}
	
	public static String parseXmlDocument(Element e, String parentName, String nodeName, int num) {
		NodeList pNode = e.getElementsByTagName(parentName);
		Node n1 = pNode.item(num);
		if (n1==null) return null;
		NodeList n2 = n1.getChildNodes();
		for (int i=0;i<n2.getLength();i++) {
			if (n2.item(i).getNodeName().equals(nodeName)) {
				String data =n2.item(i).getAttributes().getNamedItem("data").getNodeValue();
					Util.log("parseXmlDocumentList===>>"+data);
				return KMStringUtil.getStr(data);
			}
		}
		return null;
	}
	
	private static String coverNode(NodeList list) {
		StringBuffer bf = new StringBuffer();
		for (int i=0;i<list.getLength();i++) {
			bf.append(list.item(i).getNodeValue());
		}
		return KMStringUtil.getStr(bf.toString());
	}
	
	/**
	 * 리스트의 사이즈를 변환하여 반환한다.
	 * @param minSize 리스트 객체가 해당 값보다 작으면 Null로 해당 값만큼 채워준다.
	 * @param list
	 */
	public static void setListSize(int minSize ,List<?> list ){
		if(list == null)
			list = new ArrayList<Object>();
		int listSize =list.size();
		if(listSize<minSize){
			for(int i =0 ; i<minSize - listSize ; i++)
				list.add(null);
		}
	}
	

	public static Bitmap getBitmapImage(String url, boolean downSampling) {
		Bitmap bm = null;
		HttpURLConnection conn = null;
		BufferedInputStream bis = null;
		if (url==null) return null;
		try {
			URL imageURL = getUrls(url);
			conn = (HttpURLConnection) imageURL.openConnection();
			bis = new BufferedInputStream(conn.getInputStream(), 1024);
			if (downSampling) {
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 2;
				bm = BitmapFactory.decodeStream(bis, null, options);
			} else {
				bm = BitmapFactory.decodeStream(bis);
			}
		} catch (Exception e) {
			Util.logError("URL = "+url);
			Util.logError(e);
		} finally {
		      try {
		          if (bis != null)	bis.close();
		          if (conn != null)	conn.disconnect();
		        } catch (Exception e) {
		        	Util.logError(e);
		        }
		}
		return bm;
	}
	/**
	 * 안드로이드의 버그로 인해 동일한 주소인데도 Marformed IPv6 관련 오류가 발생할 수 있다.
	 * 해당 부분을 해결하기 위해 아래와 같이 사용할수 있다.
	 * 참고 : http://stackoverflow.com/questions/6811482/use-url-on-android-throws-ioexception-malformed-ipv6-address
	 * 
	 * @param url
	 * @return
	 */
	public static URL getUrls(final String ourl) {
		Util.log("url : "+ ourl);
		String[] vers = new String[4];
		String url = ourl.toString();
		URL rurl = null;
		try {
			if (url.toLowerCase().startsWith("http://")) vers[0]= "http";
			else if (url.toLowerCase().startsWith("https://")) vers[0] = "https";
			else vers[0]= "http"; 
			
			if (url.indexOf("://")>-1) {
				url = url.substring(url.indexOf("://")+3);
			}
			if (url.indexOf(":")>-1) {
				vers[1] = url.substring(0,url.indexOf(":"));
				vers[2] = url.substring(url.indexOf(":")+1, url.indexOf("/"));
			} else {
				vers[1] = url.substring(0,url.indexOf("/"));
				vers[2] = "80";
			}
			vers[3] = url.substring(url.indexOf("/"));
		}catch (Exception e) {
			Util.logError(e);
			try {
				rurl = new URL(ourl);
			}catch (Exception e1){
				Util.logError(e1);
			}
			return rurl;
		}
		
		try {
			rurl = new URL(vers[0], vers[1], Integer.parseInt(vers[2]), vers[3]);
		}	catch (Exception e) {
			Util.logError(e);
		}
		return rurl;
	}
    
}
